"""
综合技术分析主程序
集成RSI反弹检测和MACD底背离分析，在一张图上展示
"""

import os
import sys
from datetime import datetime
from combined_analyzer import CombinedTechnicalAnalyzer
from data_fetcher import CryptoDataFetcher
import argparse
import logging
import json
import csv
import time


# 设置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

def main():
    """主函数"""
    
    # 命令行参数解析
    parser = argparse.ArgumentParser(description='综合技术分析工具 - RSI反弹 + MACD底背离')
    
    # 基本参数
    parser.add_argument('--symbol', type=str, default='BTCUSDT', 
                       help='交易对符号 (默认: BTCUSDT)')
    parser.add_argument('--days', type=int, default=30, 
                       help='分析天数 (默认: 30)')
    parser.add_argument('--interval', type=str, default='4h', 
                       help='K线间隔 (默认: 4h)')
    
    # RSI参数
    parser.add_argument('--rsi-period', type=int, default=14, 
                       help='RSI计算周期 (默认: 14)')
    parser.add_argument('--rsi-threshold', type=float, default=30.0, 
                       help='RSI超卖阈值 (默认: 30.0)')
    
    # MACD参数
    parser.add_argument('--macd-fast', type=int, default=12, 
                       help='MACD快线周期 (默认: 12)')
    parser.add_argument('--macd-slow', type=int, default=26, 
                       help='MACD慢线周期 (默认: 26)')
    parser.add_argument('--macd-signal', type=int, default=9, 
                       help='MACD信号线周期 (默认: 9)')
    
    # 检测参数
    parser.add_argument('--min-distance', type=int, default=5, 
                       help='局部极值点最小间距 (默认: 5)')
    parser.add_argument('--lookback-window', type=int, default=10, 
                       help='寻找极值点的回望窗口 (默认: 10)')
    parser.add_argument('--max-divergence-distance', type=int, default=30, 
                       help='底背离检测的最大距离 (默认: 30)')
    
    # 其他选项
    parser.add_argument('--list-symbols', action='store_true', 
                       help='显示热门交易对列表')
    parser.add_argument('--preset', type=str, choices=['sensitive', 'standard', 'conservative'],
                       help='预设参数组合: sensitive(敏感), standard(标准), conservative(保守)')
    
    # 批量分析选项
    parser.add_argument('--batch-symbols', type=str, nargs='+',
                       help='批量分析多个交易对，例如: --batch-symbols BTCUSDT ETHUSDT BNBUSDT')
    parser.add_argument('--batch-file', type=str,
                       help='从文件读取交易对列表进行批量分析（每行一个交易对）')
    parser.add_argument('--batch-top', type=int,
                       help='分析热门前N个交易对，例如: --batch-top 10')
    parser.add_argument('--batch-all', action='store_true',
                       help='分析所有USDT计价且状态为TRADING的交易对（可能非常耗时）')
    parser.add_argument('--no-charts', action='store_true',
                       help='批量分析时不生成图表，仅保存数据')
    

    
    args = parser.parse_args()
    
    try:
        # 创建输出目录
        os.makedirs('output', exist_ok=True)
        
        # 初始化数据获取器
        print("[INFO] 正在初始化数据获取器...")
        fetcher = CryptoDataFetcher()
        

        # 如果用户要求列出交易对
        if args.list_symbols:
            print("\n[DATA] 热门交易对列表:")
            popular_symbols = fetcher.get_popular_symbols(50)
            for i, symbol in enumerate(popular_symbols, 1):
                print(f"{i:2d}. {symbol}")
            print(f"\n总共 {len(popular_symbols)} 个热门交易对")
            return
        
        # 批量分析模式
        if args.batch_symbols or args.batch_file or args.batch_top or args.batch_all:
            # 确定要分析的交易对列表
            symbols = []
            
            if args.batch_symbols:
                symbols = [s.upper() for s in args.batch_symbols]
                print(f"[BATCH] 批量分析指定的 {len(symbols)} 个交易对")
                
            elif args.batch_file:
                symbols = get_symbols_from_file(args.batch_file)
                if not symbols:
                    print("[ERROR] 无法从文件读取交易对列表")
                    return
                print(f"[BATCH] 从文件读取 {len(symbols)} 个交易对进行批量分析")
                
            elif args.batch_top:
                symbols = fetcher.get_popular_symbols(args.batch_top)
                print(f"[BATCH] 批量分析热门前 {args.batch_top} 个交易对")
            
            elif args.batch_all:
                # 获取所有USDT计价且处于TRADING状态的交易对
                symbols = fetcher.get_available_symbols('USDT')
                print(f"[BATCH] 批量分析所有交易对，共 {len(symbols)} 个")
            
            if not symbols:
                print("[ERROR] 没有找到要分析的交易对")
                return
            
            # 应用预设参数
            if args.preset:
                args = apply_preset_parameters(args)
                print(f"[PRESET] 应用预设参数: {args.preset}")
            
            # 执行批量分析
            batch_analyze_symbols(symbols, fetcher, args)
            return
        
        # 单个交易对分析模式
        if not args.symbol:
            print("[ERROR] 请指定交易对符号，或使用批量分析选项")
            print("[HINT] 使用 --help 查看所有选项")
            return
        
        # 验证交易对
        symbol = args.symbol.upper()
        if not fetcher.validate_symbol(symbol):
            print(f"[ERROR] 交易对 {symbol} 无效或不存在")
            print("[HINT] 使用 --list-symbols 查看可用的交易对")
            return
        
        # 应用预设参数
        if args.preset:
            args = apply_preset_parameters(args)
        
        # 获取交易对信息
        symbol_info = fetcher.get_symbol_info(symbol)
        if symbol_info:
            print(f"\n[CHART] 交易对信息:")
            print(f"   符号: {symbol_info['symbol']}")
            print(f"   基础货币: {symbol_info['baseAsset']}")
            print(f"   计价货币: {symbol_info['quoteAsset']}")
            print(f"   状态: {symbol_info['status']}")
        
        # 获取历史数据
        print(f"\n[INFO] 正在获取 {symbol} 最近 {args.days} 天的 {args.interval} 数据...")
        data = fetcher.get_historical_data(symbol, args.interval, args.days)
        
        if data.empty:
            print(f"[ERROR] 未能获取 {symbol} 的数据")
            return
        
        print(f"[OK] 成功获取 {len(data)} 条数据记录")
        print(f"   时间范围: {data.index[0]} 到 {data.index[-1]}")
        
        # 显示分析参数
        print(f"\n🔧 分析参数设置:")
        print(f"   RSI参数: 周期{args.rsi_period}, 超卖阈值{args.rsi_threshold}")
        print(f"   MACD参数: 快线{args.macd_fast}, 慢线{args.macd_slow}, 信号线{args.macd_signal}")
        print(f"   检测参数: 最小间距{args.min_distance}, 回望窗口{args.lookback_window}, 最大背离距离{args.max_divergence_distance}")
        if args.preset:
            print(f"   预设模式: {args.preset}")
        
        # 初始化综合分析器
        print(f"\n[INFO] 正在进行综合技术分析...")
        
        analyzer = CombinedTechnicalAnalyzer(
            rsi_period=args.rsi_period,
            rsi_oversold_threshold=args.rsi_threshold,
            macd_fast_period=args.macd_fast,
            macd_slow_period=args.macd_slow,
            macd_signal_period=args.macd_signal,
            min_distance=args.min_distance,
            lookback_window=args.lookback_window,
            max_divergence_distance=args.max_divergence_distance
        )
        
        # 执行分析
        result = analyzer.analyze_symbol_combined(data, symbol, args.days, interval=args.interval, save_chart=True, save_data=True, output_dir="output")
        
        # 显示结果摘要
        print(f"\n[DATA] 综合分析结果摘要:")
        print(f"   RSI反弹信号: {result['rsi_count']} 个")
        print(f"   MACD底背离信号: {result['divergence_count']} 个")
        print(f"   组合信号: {len(result['combined_signals'])} 个")
        print(f"   总信号数: {result['rsi_count'] + result['divergence_count']} 个")
        
        # 信号密度分析
        total_signals = result['rsi_count'] + result['divergence_count']
        if total_signals > 0:
            signal_density = total_signals / args.days
            print(f"   信号密度: {signal_density:.2f} 次/天")
            
            if len(result['combined_signals']) > 0:
                print(f"\n[TARGET] 发现 {len(result['combined_signals'])} 个强烈买入信号！")
                print(f"   最近组合信号:")
                for i, (idx, _) in enumerate(result['combined_signals'].iterrows()):
                    if i >= 3:  # 只显示最近3个
                        break
                    print(f"   {i+1}. {idx.strftime('%Y-%m-%d %H:%M')}")
        
        print(f"\n[OK] 分析完成！图表和数据已保存到 output/ 目录")
        
        # 询问是否分析其他交易对
        while True:
            choice = input("\n🤔 是否要分析其他交易对? (y/n): ").strip().lower()
            if choice in ['n', 'no', '']:
                break
            elif choice in ['y', 'yes']:
                new_symbol = input("请输入交易对符号 (如 ETHUSDT): ").strip().upper()
                if fetcher.validate_symbol(new_symbol):
                    print(f"\n[INFO] 正在分析 {new_symbol}...")
                    new_data = fetcher.get_historical_data(new_symbol, args.interval, args.days)
                    if not new_data.empty:
                        new_result = analyzer.analyze_symbol_combined(new_data, new_symbol, args.days, interval=args.interval, save_chart=True, save_data=True, output_dir="output")
                        print(f"[OK] {new_symbol} 分析完成！")
                        print(f"   RSI信号: {new_result['rsi_count']}, 底背离信号: {new_result['divergence_count']}, 组合信号: {len(new_result['combined_signals'])}")
                    else:
                        print(f"[ERROR] 无法获取 {new_symbol} 的数据")
                else:
                    print(f"[ERROR] 交易对 {new_symbol} 无效")
            else:
                print("请输入 y 或 n")
        
        print("\n[DONE] 程序运行完成！")
        
    except KeyboardInterrupt:
        print("\n\n[STOP] 用户中断程序")
    except Exception as e:
        logger.error(f"程序运行出错: {e}")
        print(f"\n[ERROR] 程序运行出错: {e}")

def batch_analyze_symbols(symbols, fetcher, args):
    """
    批量分析多个交易对
    
    Args:
        symbols: 交易对列表
        fetcher: 数据获取器
        args: 命令行参数
    
    Returns:
        批量分析结果字典
    """
    # 批量获取数据，优化API调用
    print(f"\n[BATCH] 开始批量分析 {len(symbols)} 个交易对...")
    batch_data = fetcher.get_batch_historical_data(symbols, args.interval, args.days)
    
    if not batch_data:
        print("[ERROR] 未能获取到任何数据，请检查网络连接或交易对符号")
        return {}
    
    # 初始化分析器
    analyzer = CombinedTechnicalAnalyzer(
        rsi_period=args.rsi_period,
        rsi_oversold_threshold=args.rsi_threshold,
        macd_fast_period=args.macd_fast,
        macd_slow_period=args.macd_slow,
        macd_signal_period=args.macd_signal,
        min_distance=args.min_distance,
        lookback_window=args.lookback_window,
        max_divergence_distance=args.max_divergence_distance
    )
    
    # 预计算每个交易对在时间段内的振幅与涨跌幅
    def compute_metrics(df):
        try:
            first_close = float(df['close'].iloc[0])
            last_close = float(df['close'].iloc[-1])
            max_high = float(df['high'].max())
            min_low = float(df['low'].min())
            amplitude = (max_high - min_low) / min_low if min_low > 0 else 0.0
            pct_change = (last_close - first_close) / first_close if first_close > 0 else 0.0
            return amplitude, pct_change
        except Exception:
            return 0.0, 0.0

    symbol_to_metrics = {sym: compute_metrics(df) for sym, df in batch_data.items()}

    # 并发分析阶段（数据已本地化，避免触发API限额）
    from concurrent.futures import ThreadPoolExecutor, as_completed
    max_workers = min(4, max(1, len(batch_data)))

    batch_results = {}
    failed_symbols = []

    print(f"\n[ANALYZE] 并发分析开始（工作线程: {max_workers}）...")

    def analyze_one(item):
        sym, df = item
        local_analyzer = CombinedTechnicalAnalyzer(
            rsi_period=args.rsi_period,
            rsi_oversold_threshold=args.rsi_threshold,
            macd_fast_period=args.macd_fast,
            macd_slow_period=args.macd_slow,
            macd_signal_period=args.macd_signal,
            min_distance=args.min_distance,
            lookback_window=args.lookback_window,
            max_divergence_distance=args.max_divergence_distance
        )
        res = local_analyzer.analyze_symbol_combined(
            df,
            sym,
            period_days=args.days,
            interval=args.interval,
            create_charts=not args.no_charts,
            save_data=True,
            output_dir="output"
        )
        return sym, res

    with ThreadPoolExecutor(max_workers=max_workers) as executor:
        futures = {executor.submit(analyze_one, item): item[0] for item in batch_data.items()}
        for future in as_completed(futures):
            symbol = futures[future]
            try:
                sym, results = future.result()
                if results:
                    batch_results[sym] = results
                    rsi_signals = len(results.get('rsi_signals', []))
                    divergence_signals = len(results.get('divergence_signals', []))
                    combined_signals = len(results.get('combined_signals', []))
                    print(f"[OK] {sym}: RSI信号={rsi_signals}, 底背离={divergence_signals}, 组合信号={combined_signals}")
                else:
                    failed_symbols.append(sym)
                    print(f"[WARN] {sym}: 分析失败")
            except Exception as e:
                failed_symbols.append(symbol)
                print(f"[ERROR] {symbol}: 分析出错 - {e}")

    # 生成批量分析汇总报告（含度量信息）
    save_batch_summary(batch_results, failed_symbols, args, symbol_to_metrics)
    
    print(f"\n[DONE] 批量分析完成！")
    print(f"[SUCCESS] 成功分析: {len(batch_results)} 个交易对")
    if failed_symbols:
        print(f"[FAILED] 分析失败: {len(failed_symbols)} 个交易对 ({', '.join(failed_symbols)})")
    
    return batch_results

def save_batch_summary(batch_results, failed_symbols, args, symbol_to_metrics=None):
    """保存批量分析汇总报告"""
    os.makedirs("output", exist_ok=True)
    
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    
    # 1. 保存CSV汇总
    summary_csv = f"output/batch_summary_{timestamp}.csv"
    with open(summary_csv, 'w', newline='', encoding='utf-8') as f:
        writer = csv.writer(f)
        writer.writerow(['交易对', 'RSI信号数', '底背离数', '组合信号数', '振幅(%)', '涨跌幅(%)', '分析状态'])
        
        for symbol, results in batch_results.items():
            rsi_count = len(results.get('rsi_signals', []))
            div_count = len(results.get('divergence_signals', []))
            comb_count = len(results.get('combined_signals', []))
            amp, pct = (0.0, 0.0)
            if symbol_to_metrics and symbol in symbol_to_metrics:
                amp, pct = symbol_to_metrics[symbol]
            writer.writerow([symbol, rsi_count, div_count, comb_count, f"{amp*100:.2f}", f"{pct*100:.2f}", '成功'])
        
        for symbol in failed_symbols:
            writer.writerow([symbol, 0, 0, 0, '', '', '失败'])
    
    # 2. 保存详细的JSON报告
    summary_json = f"output/batch_detailed_{timestamp}.json"
    summary_data = {
        'analysis_time': timestamp,
        'parameters': {
            'interval': args.interval,
            'days': args.days,
            'rsi_period': args.rsi_period,
            'rsi_oversold': args.rsi_threshold,
            'rsi_bounce_threshold': 5.0,
            'macd_fast': args.macd_fast,
            'macd_slow': args.macd_slow,
            'macd_signal': args.macd_signal,
            'lookback_window': args.lookback_window,
            'max_divergence_distance': args.max_divergence_distance,
        },
        'results': batch_results,
        'metrics': {
            symbol: {
                'amplitude': (symbol_to_metrics.get(symbol, (0.0, 0.0))[0] if symbol_to_metrics else 0.0),
                'pct_change': (symbol_to_metrics.get(symbol, (0.0, 0.0))[1] if symbol_to_metrics else 0.0)
            }
            for symbol in batch_results.keys()
        },
        'failed_symbols': failed_symbols,
        'summary': {
            'total_symbols': len(batch_results) + len(failed_symbols),
            'successful': len(batch_results),
            'failed': len(failed_symbols)
        }
    }
    
    with open(summary_json, 'w', encoding='utf-8') as f:
        json.dump(summary_data, f, ensure_ascii=False, indent=2, default=str)
    
    # 3. 不再生成文本报告（仅输出CSV与JSON）
    print(f"\n[REPORT] 批量分析报告已保存:")
    print(f"   CSV汇总: {summary_csv}")
    print(f"   详细JSON: {summary_json}")

def get_symbols_from_file(filepath):
    """从文件读取交易对列表"""
    symbols = []
    try:
        with open(filepath, 'r', encoding='utf-8') as f:
            for line in f:
                symbol = line.strip().upper()
                if symbol and not symbol.startswith('#'):  # 忽略空行和注释
                    symbols.append(symbol)
        return symbols
    except Exception as e:
        print(f"[ERROR] 读取文件失败: {e}")
        return []

def apply_preset_parameters(args):
    """应用预设参数组合"""
    
    if args.preset == 'sensitive':
        # 敏感模式：更多信号，适合短线交易
        args.rsi_period = 10
        args.rsi_threshold = 30
        args.macd_fast = 8
        args.macd_slow = 17
        args.macd_signal = 5
        args.min_distance = 4
        args.lookback_window = 10
        args.max_divergence_distance = 50
        print("[TARGET] 应用敏感模式参数（适合短线交易）")
        
    elif args.preset == 'standard':
        # 标准模式：平衡的参数设置
        args.rsi_period = 14
        args.rsi_threshold = 30
        args.macd_fast = 12
        args.macd_slow = 26
        args.macd_signal = 9
        args.min_distance = 5
        args.lookback_window = 10
        args.max_divergence_distance = 30
        print("[STANDARD] 应用标准模式参数（平衡设置）")
        
    elif args.preset == 'conservative':
        # 保守模式：更可靠的信号，适合长线投资
        args.rsi_period = 21
        args.rsi_threshold = 25
        args.macd_fast = 15
        args.macd_slow = 35
        args.macd_signal = 12
        args.min_distance = 10
        args.lookback_window = 15
        args.max_divergence_distance = 50
        print("[SAFE] 应用保守模式参数（适合长线投资）")
    
    return args

def interactive_mode():
    """交互式模式"""
    print("=" * 70)
    print("[START] 综合技术分析工具 - 交互式模式")
    print("   集成RSI反弹检测和MACD底背离分析")
    print("=" * 70)
    
    # 初始化
    fetcher = CryptoDataFetcher()
    
    # 选择交易对
    print("\n[DATA] 热门交易对:")
    popular_symbols = fetcher.get_popular_symbols(20)
    for i, symbol in enumerate(popular_symbols, 1):
        print(f"{i:2d}. {symbol}")
    
    while True:
        try:
            symbol_input = input(f"\n请选择交易对 (输入数字1-{len(popular_symbols)} 或直接输入符号): ").strip()
            
            if symbol_input.isdigit():
                index = int(symbol_input) - 1
                if 0 <= index < len(popular_symbols):
                    symbol = popular_symbols[index]
                    break
                else:
                    print("[ERROR] 数字超出范围")
                    continue
            else:
                symbol = symbol_input.upper()
                if fetcher.validate_symbol(symbol):
                    break
                else:
                    print("[ERROR] 无效的交易对")
                    continue
        except:
            print("[ERROR] 输入格式错误")
            continue
    
    # 选择预设模式
    print("\n🔧 参数设置模式:")
    print("   1. 敏感模式 - 更多信号，适合短线交易")
    print("   2. 标准模式 - 平衡设置，适合一般用户")
    print("   3. 保守模式 - 可靠信号，适合长线投资")
    print("   4. 自定义模式 - 手动设置所有参数")
    
    while True:
        try:
            mode_choice = input("\n请选择模式 (1-4): ").strip()
            if mode_choice in ['1', '2', '3', '4']:
                break
            else:
                print("[ERROR] 请输入1-4之间的数字")
        except:
            print("[ERROR] 输入格式错误")
    
    # 设置基本参数
    days = int(input("\n请输入分析天数 (默认30): ") or "30")
    interval = input("请输入K线间隔 (1h/4h/1d, 默认4h): ") or "4h"
    
    # 根据模式设置参数
    # 创建临时args对象来使用apply_preset_parameters函数
    import argparse
    temp_args = argparse.Namespace()
    
    if mode_choice == '1':  # 敏感模式
        temp_args.preset = 'sensitive'
        temp_args = apply_preset_parameters(temp_args)
        analyzer = CombinedTechnicalAnalyzer(
            rsi_period=temp_args.rsi_period, 
            rsi_oversold_threshold=temp_args.rsi_threshold,
            macd_fast_period=temp_args.macd_fast, 
            macd_slow_period=temp_args.macd_slow, 
            macd_signal_period=temp_args.macd_signal,
            min_distance=temp_args.min_distance, 
            lookback_window=temp_args.lookback_window,
            max_divergence_distance=temp_args.max_divergence_distance
        )
        print("[TARGET] 已设置为敏感模式")
        
    elif mode_choice == '2':  # 标准模式
        temp_args.preset = 'standard'
        temp_args = apply_preset_parameters(temp_args)
        analyzer = CombinedTechnicalAnalyzer(
            rsi_period=temp_args.rsi_period, 
            rsi_oversold_threshold=temp_args.rsi_threshold,
            macd_fast_period=temp_args.macd_fast, 
            macd_slow_period=temp_args.macd_slow, 
            macd_signal_period=temp_args.macd_signal,
            min_distance=temp_args.min_distance, 
            lookback_window=temp_args.lookback_window,
            max_divergence_distance=temp_args.max_divergence_distance
        )
        print("[STANDARD] 已设置为标准模式")
        
    elif mode_choice == '3':  # 保守模式
        temp_args.preset = 'conservative'
        temp_args = apply_preset_parameters(temp_args)
        analyzer = CombinedTechnicalAnalyzer(
            rsi_period=temp_args.rsi_period, 
            rsi_oversold_threshold=temp_args.rsi_threshold,
            macd_fast_period=temp_args.macd_fast, 
            macd_slow_period=temp_args.macd_slow, 
            macd_signal_period=temp_args.macd_signal,
            min_distance=temp_args.min_distance, 
            lookback_window=temp_args.lookback_window,
            max_divergence_distance=temp_args.max_divergence_distance
        )
        print("[SAFE] 已设置为保守模式")
        
    else:  # 自定义模式
        print("\n[DATA] RSI参数设置:")
        rsi_period = int(input("  RSI计算周期 (默认14): ") or "14")
        rsi_threshold = float(input("  RSI超卖阈值 (默认30): ") or "30")
        
        print("\n[CHART] MACD参数设置:")
        macd_fast = int(input("  快线周期 (默认12): ") or "12")
        macd_slow = int(input("  慢线周期 (默认26): ") or "26")
        macd_signal = int(input("  信号线周期 (默认9): ") or "9")
        
        print("\n[SEARCH] 检测参数设置:")
        min_distance = int(input("  局部极值点最小间距 (默认5): ") or "5")
        lookback_window = int(input("  回望窗口大小 (默认10): ") or "10")
        max_divergence_distance = int(input("  最大背离距离 (默认30): ") or "30")
        
        analyzer = CombinedTechnicalAnalyzer(
            rsi_period=rsi_period, rsi_oversold_threshold=rsi_threshold,
            macd_fast_period=macd_fast, macd_slow_period=macd_slow, macd_signal_period=macd_signal,
            min_distance=min_distance, lookback_window=lookback_window,
            max_divergence_distance=max_divergence_distance
        )
        print("🔧 已设置为自定义模式")
    
    print(f"\n[INFO] 开始分析 {symbol}...")
    
    # 执行分析
    try:
        data = fetcher.get_historical_data(symbol, interval, days)
        if data.empty:
            print("[ERROR] 无法获取数据")
            return
        
        result = analyzer.analyze_symbol_combined(data, symbol, days, interval=interval, save_chart=True, save_data=True, output_dir="output")
        
        print("\n[OK] 综合分析完成！")
        print(f"   RSI反弹信号: {result['rsi_count']} 个")
        print(f"   MACD底背离信号: {result['divergence_count']} 个")
        print(f"   组合信号: {len(result['combined_signals'])} 个")
        
        if len(result['combined_signals']) > 0:
            print(f"\n[TARGET] 恭喜！发现 {len(result['combined_signals'])} 个强烈买入信号！")
        
    except Exception as e:
        print(f"[ERROR] 分析过程中出错: {e}")

if __name__ == "__main__":
    if len(sys.argv) == 1:
        # 如果没有命令行参数，启动交互式模式
        interactive_mode()
    else:
        # 有命令行参数，使用命令行模式
        main()

